package com.jianyun.jyzs.receive;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.jianyun.jyzs.MainActivity;
import com.jianyun.jyzs.ThisApp;
import com.jianyun.jyzs.activity.AnnouncementActivity;
import com.jianyun.jyzs.activity.AnnouncementDetialActivity;
import com.jianyun.jyzs.activity.EngineeringDynamicActivity;
import com.jianyun.jyzs.activity.FlowExamineActivity;
import com.jianyun.jyzs.activity.TestActivity;
import com.jianyun.jyzs.activity.WarningActivity;
import com.jianyun.jyzs.bean.EdMessageBean;
import com.jianyun.jyzs.bean.EnginnerMsgResult;
import com.jianyun.jyzs.bean.MessageData;
import com.jianyun.jyzs.dao.AnnouncementDao;
import com.jianyun.jyzs.dao.EnginnerMsgDao;
import com.jianyun.jyzs.dao.ItemModel;
import com.jianyun.jyzs.dao.ModelDao;
import com.jianyun.jyzs.db.EventCount;
import com.jianyun.jyzs.db.PushEvent;
import com.jianyun.jyzs.http.Api;
import com.jianyun.jyzs.http.CustomCallback;
import com.jianyun.jyzs.http.RetrofitHelper;
import com.jianyun.jyzs.utils.ExampleUtil;
import com.jianyun.jyzs.utils.LocalSp;
import com.jianyun.jyzs.utils.Logger;
import com.jianyun.jyzs.utils.LoginCache;
import com.jianyun.jyzs.utils.SPUtils;
import com.jianyun.jyzs.widget.badge.BadgeHandler;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;
import java.util.List;

import cn.jpush.android.api.JPushInterface;
import io.rong.eventbus.EventBus;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * Created by yangshijun on 2018/6/28.
 * JPush中接收推送
 */

public class MyJPushReceiver extends BroadcastReceiver {
    private static final String TAG = "test";
    private String userId = "";
    private String enterpriseCode;
    private EnginnerMsgDao enginnerMsgDao;
    private ModelDao modelDao;

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            userId = LoginCache.getInstance().getUserInfo().getUserId();
            enterpriseCode = LoginCache.getInstance().getLoginCache().getEnterpriseCode();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (modelDao == null) {
            modelDao = new ModelDao(context);

        }
        if (enginnerMsgDao == null) {
            try {
                enginnerMsgDao = new EnginnerMsgDao(context);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        try {
            Bundle bundle = intent.getExtras();
            Logger.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));

            if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
                String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
                Logger.d(TAG, "[MyReceiver] 接收Registration Id : " + regId);
                //send the Registration Id to your server...

            } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
                String title = bundle.getString(JPushInterface.EXTRA_TITLE);
                String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
                String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
                Logger.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));

                JSONObject jsonObject = new JSONObject(extras);
                String extra = jsonObject.getString("extra");
                processCustomMessage(context, bundle);
                switch (extra) {
                    case "newsCreate":
                        //通知公告详情
                        String newsId = jsonObject.getString("news");
                        //操作 增加消息提醒
                        AnnouncementDao dao = new AnnouncementDao(context);

                        //AnnouncementsHttpHelper.getSinglAnnoucement(dao, newsId);
                        ItemModel model1 = modelDao.getModel(userId, enterpriseCode, "通知公告");
                        model1.setUnRead(true);
                        modelDao.update(model1);
                        EventBus.getDefault().post(new PushEvent(4));
                        break;
                    case "alarmUserCreate":
                        //预警消息

                        break;
                    case "workflow_count":
                        //流程待办总数
                        String workflowcount = jsonObject.getString("count");
                        SPUtils.put(context, userId, Integer.parseInt(workflowcount));
                        ThisApp.badgecount = Integer.parseInt(workflowcount);
                        BadgeHandler.getInstance().updateBadgeCount(ThisApp.badgecount);
                        ItemModel model = modelDao.getModel(userId, enterpriseCode, "流程审批");
                        model.setUnRead(true);
                        modelDao.update(model);
                        EventBus.getDefault().post(new PushEvent(4));
                        EventBus.getDefault().post(new EventCount("workflow_count", Integer.parseInt(workflowcount)));
                        break;
                    case "projectprogress":
                        //工程动态

                        break;
                    case "Discuss":
                        //评论
                        //评论消息加入到消息列表中
                        LocalSp.getInstance().setEdMessageList(new EdMessageBean(1, "", "", ""));
                        EventBus.getDefault().post(new PushEvent(3));
                        String ProjectProgress1 = jsonObject.getString("ProjectProgress");
                        String autoid1 = jsonObject.getString("autoid");
                        getEnginnMsg(enterpriseCode, ProjectProgress1, autoid1, "Discuss");
                        break;
                    case "Discuss&Discuss":
                        //回复评论
                        LocalSp.getInstance().setEdMessageList(new EdMessageBean(1, "", "", ""));
                        EventBus.getDefault().post(new PushEvent(3));
                        String ProjectProgress2 = jsonObject.getString("ProjectProgress");
                        String autoid2 = jsonObject.getString("autoid");
                        getEnginnMsg(enterpriseCode, ProjectProgress2, autoid2, "Discuss");
                        break;
                    case "Agree":
                        //点赞
                        //点赞消息加入到消息列表中
                        LocalSp.getInstance().setEdMessageList(new EdMessageBean(0, null, "", ""));
                        EventBus.getDefault().post(new PushEvent(2));
                        String ProjectProgress3 = jsonObject.getString("ProjectProgress");
                        String autoida3 = jsonObject.getString("autoid");
                        getEnginnMsg(enterpriseCode, ProjectProgress3, autoida3, "Agree");
                        break;
                }
            } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
                Log.i(TAG, "[MyReceiver] 接收到推送下来的通知");
                String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
                JSONObject jsonObject = new JSONObject(extras);
                String extra = jsonObject.getString("extra");
                Log.i(TAG, "[MyReceiver] 接收到推送下来的通知:" + jsonObject.toString());
                switch (extra) {
                    case "newsCreate":
                        //通知公告详情
                        String newsId = jsonObject.getString("news");
                        //操作 增加消息提醒
                        AnnouncementDao dao = new AnnouncementDao(context);

                        //AnnouncementsHttpHelper.getSinglAnnoucement(dao, newsId);
                        ItemModel model1 = modelDao.getModel(userId, enterpriseCode, "通知公告");
                        model1.setUnRead(true);
                        modelDao.update(model1);
                        EventBus.getDefault().post(new PushEvent(4));
                        break;
                    case "alarmUserCreate":
                        //预警消息

                        break;
                    case "workflow_count":
                        //流程待办总数
                        String workflowcount = jsonObject.getString("count");
                        SPUtils.put(context, userId, Integer.parseInt(workflowcount));
                        ThisApp.badgecount = Integer.parseInt(workflowcount);
                        BadgeHandler.getInstance().updateBadgeCount(ThisApp.badgecount);
                        ItemModel model = modelDao.getModel(userId, enterpriseCode, "流程审批");
                        model.setUnRead(true);
                        modelDao.update(model);
                        EventBus.getDefault().post(new PushEvent(4));
                        EventBus.getDefault().post(new EventCount("workflow_count", Integer.parseInt(workflowcount)));
                        break;
                    case "projectprogress":
                        //工程动态

                        break;
                    case "Discuss":
                        //评论
                        //评论消息加入到消息列表中
                        LocalSp.getInstance().setEdMessageList(new EdMessageBean(1, "", "", ""));
                        EventBus.getDefault().post(new PushEvent(3));
                        String ProjectProgress1 = jsonObject.getString("ProjectProgress");
                        String autoid1 = jsonObject.getString("autoid");
                        getEnginnMsg(enterpriseCode, ProjectProgress1, autoid1, "Discuss");
                        break;
                    case "Discuss&Discuss":
                        //回复评论
                        LocalSp.getInstance().setEdMessageList(new EdMessageBean(1, "", "", ""));
                        EventBus.getDefault().post(new PushEvent(3));
                        String ProjectProgress2 = jsonObject.getString("ProjectProgress");
                        String autoid2 = jsonObject.getString("autoid");
                        getEnginnMsg(enterpriseCode, ProjectProgress2, autoid2, "Discuss");
                        break;
                    case "Agree":
                        //点赞
                        //点赞消息加入到消息列表中
                        LocalSp.getInstance().setEdMessageList(new EdMessageBean(0, null, "", ""));
                        EventBus.getDefault().post(new PushEvent(2));
                        String ProjectProgress3 = jsonObject.getString("ProjectProgress");
                        String autoida3 = jsonObject.getString("autoid");
                        getEnginnMsg(enterpriseCode, ProjectProgress3, autoida3, "Agree");
                        break;
                }
                Log.i(TAG, "[MyReceiver] 接收到推送下来的通知: " + extras);

            } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {

                Log.i(TAG, "[MyReceiver] 用户点击打开了通知");

                String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
                JSONObject jsonObject = new JSONObject(extras);
                String extra = jsonObject.getString("extra");
                switch (extra) {
                    case "newsCreate":
                        //通知公告详情
                        Intent intent1 = new Intent(context, AnnouncementActivity.class);
                        String newsId = jsonObject.getString("newsId");
                        intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        intent1.putExtra("newsId", newsId);
                        context.startActivity(intent1);
                        break;
                    case "alarmUserCreate":
                        //预警消息
                        Intent intent2 = new Intent(context, WarningActivity.class);
                        String alarmUserId = jsonObject.getString("alarmUserId");
                        intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        intent2.putExtra("alarmUserId", alarmUserId);
                        context.startActivity(intent2);
                        break;
                    case "workflow_count":
                        //流程待办总数
                        Intent intent3 = new Intent(context, FlowExamineActivity.class);
                        String count = jsonObject.getString("count");
                        intent3.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        intent3.putExtra("count", count);
                        context.startActivity(intent3);
                        break;
                    case "projectprogress":
                        //工程动态
                        Intent intent4 = new Intent(context, EngineeringDynamicActivity.class);
                        intent4.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        context.startActivity(intent4);
                        break;
                    case "Discuss":
                        //评论

                        Intent intent5 = new Intent(context, EngineeringDynamicActivity.class);
                        intent5.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        context.startActivity(intent5);
                        break;
                    case "Discuss&Discuss":
                        //回复评论
                        Intent intent6 = new Intent(context, EngineeringDynamicActivity.class);
                        intent6.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        context.startActivity(intent6);
                        break;
                    case "Agree":
                        //点赞

                        Intent intent7 = new Intent(context, EngineeringDynamicActivity.class);
                        intent7.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        context.startActivity(intent7);
                        break;
                }

            } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
                Logger.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
                //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..

            } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
                boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
                Logger.w(TAG, "[MyReceiver]" + intent.getAction() + " connected state change to " + connected);
            } else {
                Logger.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public void getEnginnMsg(String enterpriseCode, String ProjectProgress, String autoid, String Type) {
        Log.i("test", "参数ProjectProgress：" + ProjectProgress + "***autoid:" + autoid + "***Type:" + Type);
        Api api = RetrofitHelper.builderCeshiHttp().create(Api.class);
        api.getEnginerMeessageList("GeProjectProgressByProjectAgreeAndDiscussByProgressId",
                enterpriseCode, ProjectProgress, autoid, Type,"jyzs", "Android", "1.0.2")
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new CustomCallback<EnginnerMsgResult>() {
                    @Override
                    protected void onResponse(EnginnerMsgResult response) {
                        if (response.getResult()) {
                            List<MessageData> listdata = response.getMessageData();
                            Log.i("test", "广播数据：" + listdata.toString());
                            for (int i = 0; i < listdata.size(); i++) {
                                MessageData messageData = listdata.get(i);
                                String headerUrl = response.getHeaderUrl();
                                String type = response.getType();
                                String autoid1 = response.getAttachment().getAutoid();
                                String type1 = response.getAttachment().getTYPE1();
                                String path1 = response.getAttachment().getPath1();
                                String projectProgress = response.getProjectProgress();
                                messageData.setUserId(userId);
                                messageData.setAutoids(autoid1);
                                messageData.setHeaderUrl(headerUrl);
                                messageData.setType(type);
                                messageData.setPath1(path1);
                                messageData.setTYPE1(type1);
                                messageData.setProjectProgress(projectProgress);
                                enginnerMsgDao.insert(messageData);
                            }
                            List<MessageData> enginmsgByUserId = enginnerMsgDao.getEnginmsgByUserId(userId);
                            Log.i("test","数据库数据L："+enginmsgByUserId.toString());

                        }
                    }

                    @Override
                    protected void onException(String msg) {

                    }
                });
//                .subscribe(new Subscriber<Object>() {
//                    @Override
//                    public void onError(Throwable e) {
//                        e.printStackTrace();
//                    }
//
//                    @Override
//                    public void onCompleted() {
//
//                    }
//
//                    @Override
//                    public void onNext(Object o) {
//                        Log.i("test", "o:" + o.toString());
//                    }
//                });
    }


    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
                    Logger.i(TAG, "This message has no Extra data");
                    continue;
                }

                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it = json.keys();

                    while (it.hasNext()) {
                        String myKey = it.next();
                        sb.append("\nkey:" + key + ", value: [" +
                                myKey + " - " + json.optString(myKey) + "]");
                    }
                } catch (JSONException e) {
                    Logger.e(TAG, "Get message extra JSON error!");
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.get(key));
            }
        }
        return sb.toString();
    }

    //send msg to MainActivity
    private void processCustomMessage(Context context, Bundle bundle) {
        if (MainActivity.isForeground) {
            String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
            String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
            Intent msgIntent = new Intent(MainActivity.MESSAGE_RECEIVED_ACTION);
            msgIntent.putExtra(MainActivity.KEY_MESSAGE, message);
            if (!ExampleUtil.isEmpty(extras)) {
                try {
                    JSONObject extraJson = new JSONObject(extras);
                    if (extraJson.length() > 0) {
                        msgIntent.putExtra(MainActivity.KEY_EXTRAS, extras);
                    }
                } catch (JSONException e) {

                }

            }
            LocalBroadcastManager.getInstance(context).sendBroadcast(msgIntent);
        }
    }
}

